from datetime import datetime as dt
from random import random
import re
import urllib3
import json
import pickle
import oss2
import os


class MyData:
    def __init__(self, phone : str = "15399900725"):
        # 五方科技服务器登录
        self.http = urllib3.PoolManager()
        self.user_detail = ""
        self.username = phone
        self.register_id = "e6bb39690dd279bf"
        self.password = "65ae7ef0b205881fb6a10489115c7c8f"
        self.rid = "1104a897926dae68d6c"
        self._fix_filename = ""
        self.access_token = ""
        self.url_is_recorded = "http://api.wufangedu.com:8097/appapi/oa/findAttendanceByDayV2"
        self.url_record = "http://api.wufangedu.com:8080/api/teach_atten"
        self.url_login = "http://api.wufangedu.com:8080/api/login"
        self.url_sub_user = "http://api.wufangedu.com:8080/api/subUser"
        self.url_bindid = "http://api.wufangedu.com:8080/api/push/bind_rid"
        self.url_get_oss_token = "http://api.wufangedu.com:8080/aliyun/assumeRole?username=%s&accessToken=%s"
        self.url_record_list = "http://api.wufangedu.com:8097/appapi/oa/findOaAttendanceList?access_token=%s&pageIndex=%d&pageSize=%d"
        self.pic_url_list = [
            "/attendance_teacher/image/202111/358616378852933703_960_1280.jpg",
            "/attendance_teacher/image/202111/777916378283642833_960_1280.jpg",
            "/attendance_teacher/image/202111/533916378002711533_960_1280.jpg",
            "/attendance_teacher/image/202111/284316377415995373_960_1280.jpg",
            "/attendance_teacher/image/202111/050216377138735503_960_1280.jpg",
            "/attendance_teacher/image/202111/916816376260580643_960_1280.jpg",
            "/attendance_teacher/image/202111/934416375915199363_960_1280.jpg",
            "/attendance_teacher/image/202111/586116375406536763_960_1280.jpg",
            "/attendance_teacher/image/202111/999216372804275083_1280_960.jpg",
            "/attendance_teacher/image/202111/474216371946673803_960_1280.jpg",
            "/attendance_teacher/image/202111/511216371360406353_960_1280.jpg",
            "/attendance_teacher/image/202111/440316371102615163_960_1280.jpg",
            "/attendance_teacher/image/202111/953816370504073793_960_1280.jpg",
            "/attendance_teacher/image/202111/150516370231176613_960_1280.jpg",
            "/attendance_teacher/image/202111/260716369645887763_960_1280.jpg",
            "/attendance_teacher/image/202111/152516369360164573_960_1280.jpg",
            "/attendance_teacher/image/202111/755716367619777753_960_1280.jpg",
            "/attendance_teacher/image/202111/486916367043272373_960_1280.jpg",
            "/attendance_teacher/image/202111/519716366752472543_960_1280.jpg",
            "/attendance_teacher/image/202111/743616366187479673_960_1280.jpg",
            "/attendance_teacher/image/202111/356416365316592893_960_1280.jpg",
            "/attendance_teacher/image/202111/856916365035690633_960_1280.jpg",
            "/attendance_teacher/image/202111/484616364458543803_960_1280.jpg",
            "/attendance_teacher/image/202111/804616364163380823_960_1280.jpg",
            "/attendance_teacher/image/202111/909916363591465423_960_1280.jpg",
            "/attendance_teacher/image/202111/160016363299152713_960_1280.jpg",
            "/attendance_teacher/image/202111/709116360992325453_960_1280.jpg",
            "/attendance_teacher/image/202111/303116360706794273_960_1280.jpg",
            "/attendance_teacher/image/202111/319716359855690003_960_1280.jpg",
            "/attendance_teacher/image/202111/816916359267127653_960_1280.jpg",
            "/attendance_teacher/image/202111/388916359085003143_960_1280.jpg",
            "/attendance_teacher/image/202111/737416358498985293_960_1280.jpg",
            "/attendance_teacher/image/202111/297716358162602043_960_1280.jpg",
            "/attendance_teacher/image/202111/537316357543928113_960_1280.jpg",
            "/attendance_teacher/image/202111/025116357256918193_960_1280.jpg",
            "/attendance_teacher/image/202110/705716355525040743_960_1280.jpg",
            "/attendance_teacher/image/202110/559316354964023043_960_1280.jpg",
            "/attendance_teacher/image/202110/194816354656526403_960_1280.jpg",
            "/attendance_teacher/image/202110/607216353814619993_960_1280.jpg",
            "/attendance_teacher/image/202110/812216351499270853_960_1280.jpg",
            "/attendance_teacher/image/202110/818316351230540513_960_1280.jpg",
            "/attendance_teacher/image/202110/153216347756025663_960_1280.jpg",
            "/attendance_teacher/image/202110/414216347177540223_960_1280.jpg",
            "/attendance_teacher/image/202110/706616346902636213_960_1280.jpg",
            "/attendance_teacher/image/202110/048516346038690583_960_1280.jpg",
            "/attendance_teacher/image/202110/009216345449179783_960_1280.jpg",
            "/attendance_teacher/image/202110/107316345169272713_960_1280.jpg",
            "/attendance_teacher/image/202110/763216343426557583_960_1280.jpg",
            "/attendance_teacher/image/202110/112616342593217863_960_1280.jpg",
            "/attendance_teacher/image/202110/782116341992958113_960_1280.jpg",
            "/attendance_teacher/image/202110/287216341702419423_960_1280.jpg",
            "/attendance_teacher/image/202110/487716341122645293_960_1280.jpg",
            "/attendance_teacher/image/202110/178816340834450083_960_1280.jpg",
            "/attendance_teacher/image/202110/271216340266910953_960_1280.jpg",
            "/attendance_teacher/image/202110/567416339972484223_960_1280.jpg",
            "/attendance_teacher/image/202110/467316339403658113_960_1280.jpg",
            "/attendance_teacher/image/202110/776516339135159383_960_1280.jpg",
            "/attendance_teacher/image/202110/608316337377075343_960_1280.jpg",
            "/attendance_teacher/image/202110/912816336812263543_960_1280.jpg",
            "/attendance_teacher/image/202110/460416336514412253_960_1280.jpg",
            "/attendance_teacher/image/202109/193016329888684233_960_1280.jpg",
            "/attendance_teacher/image/202109/776516329628219783_960_1280.jpg",
            "/attendance_teacher/image/202109/349316329025582383_960_1280.jpg",
            "/attendance_teacher/image/202109/436216328728960233_960_1280.jpg",
            "/attendance_teacher/image/202109/013816328209299613_960_1280.jpg",
            "/attendance_teacher/image/202109/009116327877652513_960_1280.jpg",
            "/attendance_teacher/image/202109/553216327296626073_960_1280.jpg",
            "/attendance_teacher/image/202109/452716327010417533_960_1280.jpg",
            "/attendance_teacher/image/202109/964316325568369863_960_1280.jpg",
            "/attendance_teacher/image/202109/427716325304602383_960_1280.jpg",
            "/attendance_teacher/image/202109/904916324441616843_960_1280.jpg",
            "/attendance_teacher/image/202109/845416323840518803_960_1280.jpg",
            "/attendance_teacher/image/202109/913616323576743013_960_1280.jpg",
            "/attendance_teacher/image/202109/436716322977674793_960_1280.jpg",
            "/attendance_teacher/image/202109/967016322710030283_960_1280.jpg",
            "/attendance_teacher/image/202109/251216319531365333_960_1280.jpg",
            "/attendance_teacher/image/202109/001216319228564503_960_1280.jpg",
            "/attendance_teacher/image/202109/344716318688069603_960_1280.jpg",
            "/attendance_teacher/image/202109/192816318395520093_960_1280.jpg",
            "/attendance_teacher/image/202109/269316317822543803_960_1280.jpg",
            "/attendance_teacher/image/202109/313316317515940383_960_1280.jpg",
            "/attendance_teacher/image/202109/122316316938961263_960_1280.jpg",
            "/attendance_teacher/image/202109/490416315779929833_960_1280.jpg",
            "/attendance_teacher/image/202109/893916315230287853_960_1280.jpg",
            "/attendance_teacher/image/202109/882116314928895053_960_1280.jpg",
            "/attendance_teacher/image/202109/807216313475032613_960_1280.jpg",
            "/attendance_teacher/image/202109/565116313178034663_960_1280.jpg",
            "/attendance_teacher/image/202109/641716312611796583_960_1280.jpg",
            "/attendance_teacher/image/202109/859916312606171873_960_1280.jpg",
            "/attendance_teacher/image/202109/473116311744154223_960_1280.jpg",
            "/attendance_teacher/image/202109/871516311743826663_960_1280.jpg",
            "/attendance_teacher/image/202109/225216310884793713_960_1280.jpg",
            "/attendance_teacher/image/202109/545516310017126923_960_1280.jpg",
            "/attendance_teacher/image/202109/054916309738602733_960_1280.jpg",
            "/attendance_teacher/image/202109/935816309180694563_960_1280.jpg",
            "/attendance_teacher/image/202109/026516308890535033_960_1280.jpg",
            "/attendance_teacher/image/202109/353016305712794393_960_1280.jpg",
            "/attendance_teacher/image/202109/018916305420789243_960_1280.jpg",
            "/attendance_teacher/image/202108/968016303992952333_960_1280.jpg",
            "/attendance_teacher/image/202108/405716303691422233_960_1280.jpg",
            "/attendance_teacher/image/202108/012216303121327263_960_1280.jpg",
            "/attendance_teacher/image/202108/113316302867700153_960_1280.jpg",
            "/attendance_teacher/image/202107/181416256449241333_960_1280.jpg",
            "/attendance_teacher/image/202107/599216256185587153_960_1280.jpg",
            "/attendance_teacher/image/202107/652216255593420053_960_1280.jpg",
            "/attendance_teacher/image/202107/762716255321438763_960_1280.jpg",
            "/attendance_teacher/image/202107/439316254730855773_960_1280.jpg",
            "/attendance_teacher/image/202107/012316254459251763_960_1280.jpg",
            "/attendance_teacher/image/202107/644516251865678423_960_1280.jpg",
            "/attendance_teacher/image/202107/087516251293477363_960_1280.jpg",
            "/attendance_teacher/image/202107/197716251000024073_960_1280.jpg",
            "/attendance_teacher/image/202106/879716250400630493_960_1280.jpg",
            "/attendance_teacher/image/202106/875616250124437523_960_1280.jpg",
            "/attendance_teacher/image/202106/185216249536301953_960_1280.jpg",
            "/attendance_teacher/image/202106/362816249262909393_960_1280.jpg",
            "/attendance_teacher/image/202106/354716248677074243_960_1280.jpg",
            "/attendance_teacher/image/202106/030816248397190473_960_1280.jpg",
            "/attendance_teacher/image/202106/574316246089231613_960_1280.jpg",
            "/attendance_teacher/image/202106/756916245818459233_960_1280.jpg",
            "/attendance_teacher/image/202106/691216245217731103_960_1280.jpg",
            "/attendance_teacher/image/202106/584716244953159553_960_1280.jpg",
            "/attendance_teacher/image/202106/417216244353077483_960_1280.jpg",
            "/attendance_teacher/image/202106/664816244091397123_960_1280.jpg",
            "/attendance_teacher/image/202106/265016243491272613_960_1280.jpg",
            "/attendance_teacher/image/202106/869816243213646233_960_1280.jpg",
            "/attendance_teacher/image/202106/932716242626495373_960_1280.jpg",
            "/attendance_teacher/image/202106/250416242338426923_960_1280.jpg",
            "/attendance_teacher/image/202106/172816237449226403_960_1280.jpg",
            "/attendance_teacher/image/202106/527316237185597863_960_1280.jpg",
            "/attendance_teacher/image/202106/836116233129648293_960_1280.jpg",
            "/attendance_teacher/image/202106/956616232859650593_960_1280.jpg",
            "/attendance_teacher/image/202106/038516232286634213_960_1280.jpg",
            "/attendance_teacher/image/202106/321116231995272583_960_1280.jpg",
            "/attendance_teacher/image/202106/015616231401223193_960_1280.jpg",
            "/attendance_teacher/image/202106/378616231132372323_960_1280.jpg",
            "/attendance_teacher/image/202106/141316230537246643_960_1280.jpg",
            "/attendance_teacher/image/202106/172516230267357393_960_1280.jpg",
            "/attendance_teacher/image/202106/875016227072444863_960_1280.jpg",
            "/attendance_teacher/image/202106/234816226818633673_960_1280.jpg",
            "/attendance_teacher/image/202106/548016226238254893_960_1280.jpg",
            "/attendance_teacher/image/202106/335616225951526263_960_1280.jpg",
            "/attendance_teacher/image/202106/245416225353172833_960_1280.jpg",
            "/attendance_teacher/image/202106/480016225086792543_960_1280.jpg",
            "/attendance_teacher/image/202105/633616224489246653_960_1280.jpg",
            "/attendance_teacher/image/202105/190416224219237223_960_1280.jpg",
            "/attendance_teacher/image/202105/218216221897170553_960_1280.jpg",
            "/attendance_teacher/image/202105/291016221633395383_960_1280.jpg",
            "/attendance_teacher/image/202105/219316221024880753_960_1280.jpg",
            "/attendance_teacher/image/202105/744716220765760513_960_1280.jpg",
            "/attendance_teacher/image/202105/135016220161250933_960_1280.jpg",
            "/attendance_teacher/image/202105/270016219901548323_960_1280.jpg",
            "/attendance_teacher/image/202105/326816219297822373_960_1280.jpg",
            "/attendance_teacher/image/202105/504516219031859143_960_1280.jpg",
            "/attendance_teacher/image/202105/832016218441462163_1280_960.jpg",
            "/attendance_teacher/image/202105/087116218171431783_960_1280.jpg",
            "/attendance_teacher/image/202105/549116215847596313_960_1280.jpg",
        ]
        # 保存到阿里云服务器需要的数据
        self.access_key_id = ""
        self.access_key_secret = ""
        self.security_token = ""
        self.expiration = dt.now()
        self.endpoint = "http://oss-cn-shenzhen.aliyuncs.com"
        self.bucket_name = "com-wufang-edu"

        # 用于请求时的请求头
        self.headers = {
            "post_json": {
                'Content-Type': 'application/json; charset=utf-8',
                'Content-Length': 0,
                'Host': 'api.wufangedu.com:8080',
                'Connection': 'Keep-Alive',
                'Accept-Encoding': 'gzip',
                'User-Agent': 'okhttp/3.12.0'
            },
            "get_record_list": {
                'Content-Type': 'application/json; charset=utf-8',
                'Content-Length': 0,
                'Host': 'api.wufangedu.com:8097',
                'Connection': 'Keep-Alive',
                'Accept-Encoding': 'gzip',
                'User-Agent': 'okhttp/3.12.0'
            },
            "get_oss_token": {
                "Connection":
                "Keep-Alive",
                "Accept-Encoding":
                "gzip",
                "User-Agent":
                "Dalvik/2.1.0 (Linux; U; Android 10; MI 8 Lite MIUI/V12.5.1.0.QDTCNXM)"
            },
            "is_recorded" : {
                "Host": "api.wufangedu.com:8097",
                "Content-Type" : "application/x-www-form-urlencoded",
                "Connection": "keep-alive",
                "api-version": "1",
                "Accept": "*/*",
                "User-Agent": "Education/3.3.5 (iPhone; iOS 15.1; Scale/3.00)",
                "Accept-Language": "zh-Hans-US;q=1, en;q=0.9",
                "Content-Length": "69",
                "Accept-Encoding": "gzip, deflate"
        }
        }

        # 登录时要用到的json数据
        self._content_login_subUser = {
            "deviceType": "3",
            "registerId": "",
            "pwd": "",
            "username": ""
        }
        self._content_bindid = {
            "deviceType": "3",
            "accessToken": "",
            "rid": ""
        }
        self._content_record = {
            "access_token": "",
            "attendanceAddr": "湖南省长沙市望城区438乡道靠近望城区第二中学",
            "attendanceImg": "",
            "latitude": "28.420363",
            "remark": "",
            "accessToken": "",
            "type": "",
            "longitude": "112.934456"
        }
        self._content_is_recorded = "access_token=%s&attendanceDate=%04d%02d%02d"

    def save_info(self):
        tmp = self.http
        self.http = None
        pickle.dump(self, open(self.username, "wb"))
        self.http = tmp

    def dict2json(self, content):
        return json.dumps(content, ensure_ascii=False,
                          separators=(',', ':')).encode('utf8')

    @property
    def fix_filename(self):
        # return "/attendance_teacher/image/202111/395716380874728183_960_1280.jpg"
        return self.pic_url_list[int(random()*10000) % len(self.pic_url_list)] 
    
    @property
    def content_login_subUser(self):
        self._content_login_subUser["registerId"] = self.register_id
        self._content_login_subUser["pwd"] = self.password
        self._content_login_subUser["username"] = self.username
        body = self.dict2json(self._content_login_subUser)
        self.headers["post_json"]["Content-Length"] = len(body)
        return body

    @property
    def content_bindid(self):
        self._content_bindid["accessToken"] = self._access_token
        self._content_bindid["bid"] = self.rid
        body = self.dict2json(self._content_bindid)
        self.headers["post_json"]["Content-Length"] = len(body)
        return body

    @property
    def content_is_recorded(self):
        body = self._content_is_recorded % (self.access_token, dt.now().year, dt.now().month, dt.now().day)
        self.headers['is_recorded']['Content-Length'] = len(body)
        return body

    def content_record(self, record_type : int):
        self._content_record['access_token'] = self.access_token
        self._content_record['accessToken'] = self.access_token
        self._content_record['attendanceImg'] = self.fix_filename
        self._content_record['type'] = str(record_type)
        body = self.dict2json(self._content_record)
        self.headers['post_json']['Content-Length'] = len(body)
        return body

    def req_login(self):
        ret = None
        try:
            r = self.http.request('POST',
                                  self.url_login,
                                  body=self.content_login_subUser,
                                  headers=self.headers['post_json'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
        except:
            pass
        return ret

    def req_subUser(self):
        ret = None
        try:
            r = self.http.request('POST',
                                  self.url_sub_user,
                                  body=self.content_login_subUser,
                                  headers=self.headers['post_json'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
                self.access_token = ret['data']['tokenInfo']['access_token']
                self.user_detail = ret['data']['userDetail']
                self.save_info()
        except:
            pass
        return ret

    def req_get_record_list(self, page):
        ret = None
        try:
            url = self.url_record_list % (self.access_token, page, 100)
            r = self.http.request('GET',
                                  url,
                                  headers=self.headers['get_record_list'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
        except:
            pass
        return ret

    def req_get_oss_token(self):
        ret = None
        try:
            url = self.url_get_oss_token % (self.username, self.access_token)
            r = self.http.request('GET',
                                  url,
                                  headers=self.headers['get_oss_token'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
                self.access_key_id = ret['AccessKeyId']
                self.access_key_secret = ret['AccessKeySecret']
                self.security_token = ret['SecurityToken']
                self.expiration = dt.strptime(ret['Expiration'],
                                              '%Y-%m-%dT%H:%M:%SZ')
                self.save_info()
        except:
            print("%s 获取阿里云访问权限时异常" % dt.now())
        return ret

    def req_fix_file_exist(self):
        try:
            auth = oss2.StsAuth(self.access_key_id, self.access_key_secret,
                                self.security_token)
            bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
            exist = bucket.object_exists(self.fix_filename)
        except:
            print("%s 查找图像文件是否存在时抛出异常!" % dt.now())
            exist = None
        return exist

    def req_upload_fix_file(self):
        try:
            auth = oss2.StsAuth(self.access_key_id, self.access_key_secret,
                                self.security_token)
            bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
            bucket.put_object_from_file(self.fix_filename, 'dk.jpg')
        except:
            print("%s 上传图像文件是否存在时抛出异常!" % dt.now())

    def read_saved_info(self, username: str):
        try:
            if not os.path.exists(username) :
                return None
            data = pickle.load(open(username, 'rb'))
            self.user_detail = data.user_detail
            self.username = data.username
            self.register_id = data.register_id
            self.password = data.password
            self.rid = data.rid
            self._fix_filename = data._fix_filename
            self.access_token = data.access_token
            self.access_key_id = data.access_key_id
            self.access_key_secret = data.access_key_secret
            self.security_token = data.security_token
            self.expiration = data.expiration
            return True
        except:
            return None

    def req_make_record(self, record_type: int):
        ret = None
        try:
            r = self.http.request('POST',
                                  self.url_record,
                                  body=self.content_record(record_type),
                                  headers=self.headers['post_json'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
        except:
            pass            
        return ret

    def req_has_recorded(self):
        result = {
            "status" : False,
            "morning" : False,
            "evening" : False
        }
        try:
            r = self.http.request('POST',
                                  self.url_is_recorded,
                                  body=self.content_is_recorded,
                                  headers=self.headers['is_recorded'])
            r.release_conn()
            if r.status == 200:
                ret = json.loads(r.data)
                result['status'] = True
                for i in ret['data']['attendance']:
                    if i['type'] == 1:
                        result['morning'] = True
                    elif i['type'] == 2:
                        result['evening'] = True
        except:
            result['status'] = False
        return result

    def req_get_file(self, url : str, path : str):
        ret = None
        try:
            r = self.http.request('GET', url)
            r.release_conn()
            if r.status == 200:
                jpg_file = open(path, 'wb')
                jpg_file.write(r.data)
                jpg_file.close
        except:
            print("%s\t%s获取失败" % (dt.now(), url))   
        return ret